﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Automation;

namespace GpCommon.Helpers
{
    public class UIAutomationHelper
    {
        public static bool InvokeExpandCollapseAE(AutomationElement rootAE,AutomationProperty property, string value )
        {
            var subAE = rootAE.FindFirst(TreeScope.Subtree, new PropertyCondition(property, value));
            if (subAE == null) return false;
            var expandPt = (ExpandCollapsePattern)subAE.GetCurrentPattern(ExpandCollapsePattern.Pattern);
            if(expandPt == null) return false;
            expandPt.Expand();
            return true;
        }
        public static bool InvokeSelectionItemAE(AutomationElement rootAE, AutomationProperty property, string value)
        {
            var subAE = rootAE.FindFirst(TreeScope.Subtree, new PropertyCondition(property, value));
            if (subAE == null) return false;
            var selectPt = (SelectionItemPattern)subAE.GetCurrentPattern(SelectionItemPattern.Pattern);
            if (selectPt == null) return false;
            selectPt.Select();
            return true;
        }
        public static bool InvokeInvokeAE(AutomationElement rootAE, AutomationProperty property, string value)
        {
            var subAE = rootAE.FindFirst(TreeScope.Subtree, new PropertyCondition(property, value));
            if (subAE == null) return false;
            var invokePt = (InvokePattern)subAE.GetCurrentPattern(InvokePattern.Pattern);
            if (invokePt == null) return false;
            invokePt.Invoke();
            return true;
        }
        public static bool InvokeSetFocusAE(AutomationElement rootAE, AutomationProperty property, string value)
        {
            var subAE = rootAE.FindFirst(TreeScope.Subtree, new PropertyCondition(property, value));
            if (subAE == null) return false;
            subAE.SetFocus();
            return true;
        }

        public static Point GetMidPosition(AutomationElement rootAE, AutomationProperty property, string value)
        {
            var subAE = rootAE.FindFirst(TreeScope.Subtree, new PropertyCondition(property, value));
            var rect = subAE.Current.BoundingRectangle;
            return new Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
        }

        public static int GetIntValue(AutomationElement rootAE, AutomationProperty property, string value)
        {
            var subAE = rootAE.FindFirst(TreeScope.Subtree, new PropertyCondition(property, value));
            if (subAE == null) return -1;
            if (int.TryParse(subAE.Current.Name, out int res))
                return res;
            return -1;
        }
    }
}
